package com.wisdudu.blank.ui.common;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.orhanobut.logger.Logger;
import com.wisdudu.blank.R;
import com.wisdudu.frame.base.BaseFragment;
import com.wisdudu.blank.support.rxbus.RxBusFlag;
import com.wisdudu.frame.support.util.FileUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static android.content.ContentValues.TAG;

/**
 * Created by qyf on 2016/7/11.
 */
public class SelectImageFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener, View.OnClickListener {

    private TextView mTvSelectFromAlbum;
    private TextView mTvSelectFromCamera;
    private TextView mTvSelectFromSystem;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private final int  ALBUM_OK = 1, CAMERA_OK = 2,FLAG_MODIFY_FINISH = 3;
    private File file;//拍照路径
    private Uri uritempFile = null;
    private String picName="",urlpath="";//图片地址
    int limit = getArguments().getInt(RxBusFlag.MAX_SELECTED_IMG, 1);//选择图片最大张数
    public static SelectImageFragment newInstance(int max_img_num, boolean enable_select_img) {
        Bundle args = new Bundle();
        args.putInt(RxBusFlag.MAX_SELECTED_IMG, max_img_num);
        args.putBoolean(RxBusFlag.ENABLE_SYSTEM_IMG, enable_select_img);
        SelectImageFragment fragment = new SelectImageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        file = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
        file.delete();// 清空之前的文件
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 直接从相册获取
            case ALBUM_OK:
                //从相册中获取到图片了，才执行裁剪动作
                if (data != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            // 调用相机拍照
            case CAMERA_OK:
                // 当拍照到照片时进行裁，否则不执行操作
                if (file.exists()) {
                    startPhotoZoom(Uri.fromFile(file));
                }
            break;
            case FLAG_MODIFY_FINISH:
                if (data != null) {
                    setPicToView(data,getActivity());
                }else
                {
                    Log.e("Main","data为空");
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    @Override
    protected View initBinding(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        FragmentSelectImageBinding mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_select_image, container, false);
//        mBinding.setViewModel(new SelectImageVM(this, getArguments().getInt(RxBusFlag.MAX_SELECTED_IMG, 1)));
        View view = inflater.inflate(R.layout.fragment_select_image, container, false);
        mTvSelectFromAlbum = (TextView) view.findViewById(R.id.tv_select_from_album);
        mTvSelectFromAlbum.setOnClickListener(this);
        mTvSelectFromCamera = (TextView) view.findViewById(R.id.tv_select_from_camera);
        mTvSelectFromCamera.setOnClickListener(this);
        mTvSelectFromSystem = (TextView) view.findViewById(R.id.tv_select_from_system);
        mTvSelectFromSystem.setVisibility(getArguments().getBoolean(RxBusFlag.ENABLE_SYSTEM_IMG, false) ? View.VISIBLE : View.GONE);
        mTvSelectFromSystem.setOnClickListener(v -> addFragment(new SelectSystemImgFragment()));
        File filea = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!filea.getParentFile().exists()) filea.getParentFile().mkdirs();
        uritempFile = Uri.fromFile(filea);
        picName = getPhotoFileName();
        return view;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initToolbar(getToolbar(), "选择图片");
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        Logger.object(result.getImage());
        Logger.object(result.getImages());
        Intent intent = new Intent();
        ArrayList<String> selectedPahts = new ArrayList<>();
        for (int i = 0; i < result.getImages().size(); i++) {
            selectedPahts.add(result.getImages().get(i).getPath());
        }
        intent.putStringArrayListExtra(RxBusFlag.SELECT_IMGS, selectedPahts);
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(com.jph.takephoto.R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_select_from_album:
                if (limit > 1) {
                    configCompress(takePhoto);//压缩设置
                    takePhoto.onPickMultipleWithCrop(limit, getCropOptions());//开启剪裁
//                    takePhoto.onPickMultiple(limit);
                } else {
                    Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                    albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(albumIntent, ALBUM_OK);
                }

                break;
            case R.id.tv_select_from_camera:
                if (limit > 1) {
                    configCompress(takePhoto);//压缩设置
                    takePhoto.onPickFromCaptureWithCrop(uritempFile, getCropOptions());//相机
//                takePhoto.onPickFromCapture(imageUri);
                } else {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            // 指定调用相机拍照后的照片存储的路径
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(cameraIntent, CAMERA_OK);
        }
                break;
            default:
                break;
        }
    }

    /**
     * 开启压缩设置，否则不予调用
     */
    private void configCompress(TakePhoto takePhoto) {
//            takePhoto.onEnableCompress(null,false);//不支持压缩
        //压缩
        int maxSize = 102400;//100K
        int maxPixel = 800;//长宽最大像素 800px
        boolean showProgressBar = false;//是否显示压缩进度条
        CompressConfig config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(maxPixel).create();
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    /**
     * 开启剪裁设置剪裁参数，否则不予调用
     */
    private CropOptions getCropOptions() {

        int height = 800;//高
        int width = 800;//宽 px
        boolean withWonCrop = true;//使用自带剪裁工具，false为使用第三方工具

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);//比例
//            builder.setOutputX(width).setOutputY(height);//宽x高
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }
    /**
     * 裁剪
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
         intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, FLAG_MODIFY_FINISH);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    public void setPicToView(Intent picdata,Activity c) {
            // 取得SDCard图片路径做显示
        String path = uritempFile.getPath();
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uritempFile));
            Bitmap zoomBitmap = zoomBitmap(bitmap,450,450);
            String  urlpath = FileUtil.saveFile(getActivity(), picName, zoomBitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
            Intent intent = new Intent();
                    ArrayList<String> selectedPahts = new ArrayList<>();
                    for (int i = 0; i < 1; i++) {
                        selectedPahts.add(path);
                    }
                    intent.putStringArrayListExtra(RxBusFlag.SELECT_IMGS, selectedPahts);
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
    }
    /** 缩放Bitmap图片 **/
    public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }
}
